/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */

package com.jz.jd.rest.client;

import android.os.Build;
import android.support.annotation.NonNull;

import com.joyoung.robot.util.LogUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


public class RestClient {
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    private static final String TAG = "jy-" + RestClient.class.getSimpleName();

    private static final int DEFAULT_CONNECT_TIMEOUT = 10;
    private static final int DEFAULT_RW_TIMEOUT = 25;

    private OkHttpClient mOkHttpClient;

    private static class SingletonHolder {
        private static final RestClient INSTANCE = new RestClient();
    }

    /**
     * 获取单例
     */
    public static RestClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 因为设置了读写超时，该client不适用于上传和下载
     */
    private RestClient() {
        mOkHttpClient = new OkHttpClient.Builder()
                //log 拦截器
                .addNetworkInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        LogUtil.d(TAG, message);
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY)) // TODO: 2017/11/24 正式发布使用Basic 或去除日志打印
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(@NonNull Chain chain) throws IOException {
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                // 1:爱下厨 2:欧南多 3:onecup
//                                .addHeader("source", "1")
                                .addHeader("model", Build.MANUFACTURER + " " + Build.MODEL)
                                .addHeader("localsizeModel", "Android")
                                .addHeader("systemName", "Android " + Build.VERSION.RELEASE)
                                .addHeader("systemVersion", String.valueOf(Build.VERSION.SDK_INT))
//                                .addHeader("mobileId", "robot")
                                .addHeader("mobileName", Build.MANUFACTURER)
                                .addHeader("appVersion", "4.2.2"); // Application.getAppVersionName()
                        // Request customization: add request headers
                        Response response = chain.proceed(requestBuilder.build());
                        return response;
//                        int code;
//                        try {
//                            String bodyStr = (response.body() == null ? "" : response.body().string()); // 注意：response.body().string()仅能调用一次，不能会异常！！！
//                            JSONObject jsonObject = new JSONObject(bodyStr);
//                            code = Integer.parseInt(jsonObject.getString("code"));
//                            LogUtil.d(TAG, "HTTP code: " + code);
//                        } catch (IOException | JSONException | NumberFormatException e) {
//                            e.printStackTrace();
//                            return response;
//                        }
//                        // TODO: 2017/11/6 状态码待确定
//                        if (response.code() == 403 || code == BusinessCode.ERROR_CODE_SESSION_OUT_OF_DATE) {
//                            // TODO: 2017/11/6 跳转登录界面 FLAG_ACTIVITY_CLEAR_TASK Eventbus
//
//                            return response;
//                        } else {
//                            return response;
//                        }
                    }
                })
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_RW_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_RW_TIMEOUT, TimeUnit.SECONDS).cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public void clearSession() {
        cookieStore.clear();
    }
}
